package 动态规划;

public class Solution64 {

    public static void main(String[] args) {
        int[][] nums = new int[][]{
                {1, 3, 1}, {1, 5, 1}, {4, 2, 1}
        };
        System.out.println(minPathSum(nums));
        System.out.println(dp(nums));
    }


    public static int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        //m行n列需要走的路径
        return process(grid, grid.length - 1, grid[0].length - 1);
    }

    // 当前位置到0，0最短
    // 当前位置到右下角走的数最短的步数
    public static int process(int[][] grid, int i, int j) {
        //base
        if (i == 0 && j == 0) {
            return grid[i][j];
        }
        //左边
        if (i == 0) {
            return grid[0][j] + process(grid, i, j - 1);
        }
        //上边
        if (j == 0) {
            return grid[i][0] + process(grid, i - 1, j);
        }
        return grid[i][j] + Math.min(process(grid, i, j - 1), process(grid, i - 1, j));
    }

    public static int dp(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int N = grid.length;
        int M = grid[0].length;
        int[][] dp = new int[N][M];
        dp[0][0] = grid[0][0];
        //0行填完了
        for (int j = 1; j < M; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }
        for (int i = 1; i < N; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }
        for (int i = 1; i < N; i++) {
            for (int j = 1; j < M; j++) {
                dp[i][j] = grid[i][j] + Math.min(dp[i][j - 1], dp[i - 1][j]);
            }
        }
        return dp[N - 1][M - 1];
    }

}
